import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;


public class ServiceThread extends Thread implements MyObservable{
	public Socket socket;
	public MDChecker mdchecker;
	List<MyObserver> observers;
	public ServiceThread(Socket sock){
		observers = new ArrayList<MyObserver>();
		//getting an md5 checker:
		mdchecker = new MDChecker();
		this.socket = sock;
	}
	
	public void run(){
		try{
			notifyObservers("New connection from: "+socket.getInetAddress().getHostAddress());
			ServerGUI.log.setText(ServerGUI.log.getText()+"\nNew connection from: "+socket.getInetAddress().getHostAddress());
			DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
			//checking password:
			String recvPass = dis.readUTF();
			//checking password:
			if (mdchecker.checkPassword(recvPass) == false){
				//bad pass:
				System.out.println("Client provided a bad password.");
				//System.exit(0);
				//setChanged();
				notifyObservers("Unauthorized connection. Blocking...");
				ServerGUI.log.setText(ServerGUI.log.getText()+"\nUnauthorized connection. Blocking...");
			}
			else{
				String fileName = "";
				//setChanged();
				notifyObservers(new Integer(1));//starting transfer
				ServerGUI.transferFrame.setVisible(true);
				//reading number of files:
				int nrFiles = dis.readInt();
				System.out.println("Server: Receiving " + nrFiles+" file(s)");
				System.out.println("Saving file to: "+Server.downloadFolder);
				//reading each file as it comes:
				while(nrFiles > 0) {
					//length:
					int lengthOfFile = dis.readInt();
					//name
					fileName = dis.readUTF();
					//creating file:
					File f = new File(Server.downloadFolder+File.separator+fileName);
					//reading data:
					byte[] byteArray = new byte[lengthOfFile];
					dis.readFully(byteArray);
					//recomposing the file:
					DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
					dos.write(byteArray);
					nrFiles--;
				}
				socket.close();
				//setChanged();
				notifyObservers(new Integer(0));//finished transfer
				ServerGUI.transferFrame.setVisible(false);
			}
		} catch(IOException e){
			System.out.println(e.getMessage());
		}
	}

	@Override
	public void addObserver(MyObserver o) {
		// TODO Auto-generated method stub
		//System.out.println("face add");
		observers.add(o);
	}

	@Override
	public void notifyObservers() {
		// TODO Auto-generated method stub
		//Nothing to do here
	}

	@Override
	public void notifyObservers(Object obj) {
		// TODO Auto-generated method stub
		for (MyObserver o : this.observers){
			o.update(this,obj);
		}
	}
}
